<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const router = useRouter();
const username = ref('');
const password = ref('');

const handleLogin = async () => {
  try {
    const response = await axios.post('http://localhost:8080/user/login', {
      username: username.value,
      password: password.value
    });
    
    if (response.data.code === 0) {
      ElMessage.success("登录成功！");
      localStorage.setItem('username', username.value);
      router.push('/my');
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error('登录失败，请稍后重试');
  }
};

const reset = () => {
  username.value = '';
  password.value = '';
};
</script>

<template>
  <div class="flex flex-col items-center justify-center min-h-screen bg-background">
    <div class="p-6 rounded-lg w-full max-w-sm">
      <div class="box bg-card p-6 rounded-lg shadow-md w-full max-w-sm">
        <h1 class="text-3xl font-bold text-primary">吃啥</h1>
        <p class="text-muted-foreground text-sm mb-4">创造更健康的生活</p>
      </div>
      <el-form
          size="large"
          autocomplete="off"
          label-position="left"
      >
        <br>
        <el-form-item>
          <label class="text-muted-foreground text-sm" for="username">用户名</label>
          <el-input
              v-model="username"
              placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <label class="text-muted-foreground text-sm mt-4" for="password">密码</label>
          <el-input
              v-model="password"
              type="password"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
          <el-button @click="$router.push('/register')">注册</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
</style>
